#include "itemeditor.h"
#include "ui_itemeditor.h"
#include <QMessageBox>

ItemEditor::ItemEditor(int id, AcDB* db,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ItemEditor)
{
    ui->setupUi(this);
    ui->itemCost->setFocus();

    this->m_db = db;
    this->id = id;

    QList<QVariant> data;
    if (m_db->getItem(id, &data))
    {
        ui->itemName->setText(data[0].toString());
        ui->itemCost->setValue(data[1].toFloat());
        ui->itemDate->setDate(data[3].toDate());
        ui->itemRemark->setPlainText(data[4].toString());

    } else {
        this->close();
    }

    m_db->listClass(&typeSelections);
    for (int i = 0; i < typeSelections.size(); i++)
    {
        ui->itemType->addItem(typeSelections.at(i).at(1).toString());
        if (typeSelections.at(i).at(0).toInt() == data[2].toInt())
            ui->itemType->setCurrentIndex(i);
    }

    //ui->itemType->keyPressEvent();
}

ItemEditor::~ItemEditor()
{
    delete ui;
}

void ItemEditor::on_itemType_currentIndexChanged(int index)
{
    ui->itemRemark->setPlainText(typeSelections.at(index).at(1).toString());
}

void ItemEditor::on_cancelBt_clicked()
{
    this->close();
}

void ItemEditor::on_okBt_clicked()
{
    QList<QVariant> data;
    data.append(ui->itemName->text());
    int type = typeSelections.at(ui->itemType->currentIndex()).at(0).toInt();
    data.append(type);
    data.append(ui->itemDate->date());
    data.append(ui->itemCost->value());
    data.append(ui->itemRemark->toPlainText());
    if (m_db->updateItem(id, &data))
    {
        this->accept();
    } else {
        QMessageBox::warning(NULL, "错误", "更新错误");
    }
}

void ItemEditor::on_itemView_clicked()
{

}

void ItemEditor::on_itemChangeFile_clicked()
{

}

void ItemEditor::on_itemDeleteFile_clicked()
{

}
